using System.Collections.Generic;
using System.Linq;
using Microsoft.SharePoint;
using Sapphire.Linq.Framework;

namespace Sapphire.Linq.Mappers
{
    public class SPUserMapper : IObjectMapper
    {
        readonly Dictionary<string, SPUser> _users = new Dictionary<string, SPUser>();

        public TTo Map<TTo>(object value, object[] parameters)
        {
            var field = parameters.OfType<SPField>().First();
            return (TTo)GetUser(field.ParentList.ParentWeb, value.ToString());
        }

        private object GetUser(SPWeb web, string value)
        {
            if (!_users.ContainsKey(value))
            {
                _users[value] = SPData.GetUser(web, value);
            }
            return _users[value];
        }

        public bool IsMatch<TTo>(object value, object[] parameters)
        {
            return typeof(TTo) == typeof(SPUser);
        }
    }
}